<?php

class RequestvideoController extends Controller
{
    public $layout='//layouts/column2';
    
    public function filters()
    {
            return array(
                    'accessControl', // perform access control for CRUD operations
                    'postOnly + delete', // we only allow deletion via POST request
            );
    }
    
    public function accessRules()
        {
                return array(
                        array('allow',  // allow all users to perform 'index' and 'view' actions
                                'actions'=>array('view'),
                                'users'=>array('*'),
                        ),
                        array('allow', // allow authenticated user to perform 'create' and 'update' actions
                                'actions'=>array('index','cctvshow','create','update'),
                                'users'=>array('@'),
                        ),
                        array('allow', // allow admin user to perform 'admin' and 'delete' actions
                                'actions'=>array('admin','delete'),
                                'users'=>array('admin'),
                        ),
                        array('deny',  // deny all users
                                'users'=>array('*'),
                        ),
                );
        }

    public function actionIndex()
	{
            $cctvmappvideo = new Cctvmappingcamera();
            $cctvcamera = new Cctvcamera();
            $reqvideo = new Cctvrequestvideo();
            $username = Yii::app()->user->name;
            
            if (!Yii::app()->user->isGuest){
                $menugroup = Sysusrsecurity::model()->find('CredentialName="'.$username.'" and isLocked = "0" and ExpiredDate > "'.Date('Y-m-d').'"', array('CredentialName ASD'))->MenuGroupID;
                $cctvmappvideo = Cctvmappingcamera::model()->findAll("MenuGroupID = '{$menugroup}' and isActive  = 1");
            }
            if(isset($_POST['Cctvrequestvideo']))
            {
                $reqvideo->attributes=$_POST['Cctvrequestvideo'];
                
                $reqvideo->CredentialName = $username;
                $criteria=new CDbCriteria;
                $criteria->condition = "CredentialName = '{$username}' and ComputerName = '{$reqvideo->ComputerName}' and CameraName = '{$reqvideo->CameraName}'";
                $criteria->order = "RequestID DESC";
                $rvid = Cctvrequestvideo::model()->find($criteria);
                $maxvalue = isset($rvid)?$rvid->RequestID:0;
                $reqvideo->RequestID = $maxvalue+1;
                $reqvideo->FileName = md5($username.$reqvideo->ComputerName.$reqvideo->CameraName.rand(1000, 1000000));
                $reqvideo->RequestURL = "";
                $reqvideo->RequestExpired = date("Y-m-d H:i:s",mktime(date('H'), date('i')+1, date('s'), date('m'), date('d'), date('Y')));
                $reqvideo->isActive = 1;
                $reqvideo->createdby = $username;
                $reqvideo->createdon = Date("Y-m-d H:i:s");
                
                if($reqvideo->validate())
                {
                    $req = Cctvrequestvideo::model()->find("CredentialName = '{$username}' and ComputerName = '{$reqvideo->ComputerName}' and CameraName = '{$reqvideo->CameraName}' and isActive = 1");
                    if (!isset($req)){
                        $this->saveModel($reqvideo);
                    }
                }
            }
            
            $this->render('index', array('cctvmappvideo'=>$cctvmappvideo, 'cctvcamera'=>$cctvcamera, 'reqvideo'=>$reqvideo));
	}

        public function actionCctvshow()
	{
            $cctvmappvideo = new Cctvmappingcamera();
            $cctvcamera = new Cctvcamera();
            $reqvideo = new Cctvrequestvideo();
            $username = Yii::app()->user->name;
            
            if (!Yii::app()->user->isGuest){
                
                $menugroup = Sysusrsecurity::model()->find("credentialname='".$username."' and islocked = FALSE and expireddate > '".Date('Y-m-d')."'", array('credentialname ASD'))->menugroupid;
                $cctvmappvideo = Cctvmappingcamera::model()->findAll("menugroupid = '{$menugroup}' and isActive  = TRUE");
                
                foreach ($cctvmappvideo as $cmap){
                    $reqvideo = new Cctvrequestvideo();
                    $reqvideo->isNewRecord=TRUE;
                    $reqvideo->credentialname = $username;
                    $reqvideo->computername = $cmap->computername;
                    $reqvideo->cameraname = $cmap->cameraname;
                    $criteria=new CDbCriteria;
                    $criteria->condition = "credentialname = '{$username}' and computername = '{$cmap->computername}' and cameraname = '{$cmap->cameraname}'";
                    $criteria->order = "requestid DESC";
                    $rvid = Cctvrequestvideo::model()->find($criteria);
                    $maxvalue = isset($rvid)?$rvid->requestid:0;
                    $reqvideo->requestid = $maxvalue+1;
                    $reqvideo->filename = md5($username.$reqvideo->computername.$reqvideo->cameraname.rand(1000, 1000000));
                    $reqvideo->requesturl = "";
                    $reqvideo->requestexpired = date("Y-m-d H:i:s",mktime(date('H'), date('i')+1, date('s'), date('m'), date('d'), date('Y')));
                    $reqvideo->isactive = 1;
                    $reqvideo->createdby = $username;
                    $reqvideo->createdon = Date("Y-m-d H:i:s");
                    if($reqvideo->save()){
                        echo '<br><br><br><br><br>asdasdasd-->'.$menugroup.count($cctvmappvideo);
                    }else{
                        echo '<pre>';
                        var_dump($reqvideo->attributes);
                        echo '</pre>';
                        echo '<br><br><br><br><br>asdasdasdASSOLOLE-->'.$menugroup.count($cctvmappvideo);
                    }
                    if($reqvideo->validate())
                    {
                        $req = Cctvrequestvideo::model()->find("credentialname = '{$username}' and computername = '{$reqvideo->computername}' and cameraname = '{$reqvideo->cameraname}' and isActive = TRUE");
                        if (!isset($req)){
                            $this->saveModel($reqvideo);
                        }
                    }
                }
            }
            
            $this->render('cctvshow', array('cctvmappvideo'=>$cctvmappvideo, 'cctvcamera'=>$cctvcamera, 'reqvideo'=>$reqvideo));
	}
        
        public function loadModel($requestid, $CredentialName, $ComputerName, $CameraName)
	{
                $model=Cctvrequestvideo::model()->findByPk(array('requestid'=>$requestid, 'CredentialName'=>$CredentialName, 'ComputerName'=>$ComputerName, 'CameraName'=>$CameraName));
		if($model==null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Cctvrequestvideo $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='cctvrequestvideo-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function saveModel($model)
	{
		try
		{
			$model->save();
		}
		catch(Exception $e)
		{
			$this->showError($e);
		}		
	}
        
        function showError(Exception $e)
	{
		if($e->getCode()==23000)
			$message = "This operation is not permitted due to an existing foreign key reference.";
		else
			$message = "Invalid operation.";
		throw new CHttpException($e->getCode(), $message);
	}
        	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}